﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using EmbeddedWebserver.Core.Configuration;
using EmbeddedWebserver.Core.Helpers;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.Netduino;
using EmbeddedWebserver.Core;


namespace HttpIntfLib
{
    public class HTTPListener
    {
        public static void kickOffThreadHttp()
        {
            Thread t = new Thread(HTTPListener.KickOffHttpService);
            t.Start();
        }

        public static void KickOffHttpService()
        {
            //var config = new EmbeddedWebapplicationConfiguration(@"SD\webroot");
            var config = new EmbeddedWebapplicationConfiguration();
            
            //config.ReadConfiguration();            
            Microsoft.SPOT.Net.NetworkInformation.NetworkInterface[] networkInterfaces = Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
            foreach (var networkInterface in networkInterfaces)
            {
                DebugHelper.Print(" My Device Ip adress: " + networkInterface.IPAddress);                
            }

            using (var server = new Webserver(config))
            {
                server.RegisterHandler("/", typeof(Status));
                server.RegisterHandler("Status", typeof(Status));
                server.RegisterHandler("GPIO", typeof(GpioDriver));
                server.RegisterHandler("Analog", typeof(AnalogDriver));
                server.RegisterHandler("PWM", typeof(PwmDriver));
                server.RegisterHandler("UART", typeof(UartDriver));
                //server.RegisterThreadSafeHandler("post", new SamplePostHandler());
                server.StartListening();
                //  Go to Sleep , Another thread was created to peroform the job
                Thread.Sleep(System.Threading.Timeout.Infinite);
            }     


        }

    }


    public class HttpTestListener
    {
        public static void KickOffPortMapperHttp()
        {
            // write your code here
            // set up the LED and turn it off by default
            OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);

            // configure the port # (the standard web server port is 80)
            int port = 90;

            Debug.Print("Inside PortMapper HTTP..");
            // wait a few seconds for the Netduino Plus to get a network address.
            Thread.Sleep(5000);
            Debug.Print("Waking up from deep sleep of 5 sec ");
            // display the IP address

            Debug.Print("Socket Init Starting ..... :-) ");
            // create a socket to listen for incoming connections
            Socket listenerSocket = new Socket(AddressFamily.InterNetwork,
                                               SocketType.Stream,
                                               ProtocolType.Tcp);
            Debug.Print("Socket Init Completed ..... :-) ");
            IPEndPoint listenerEndPoint = new IPEndPoint(IPAddress.Any, port);

            Debug.Print("setting up socket");

            // bind to the listening socket
            listenerSocket.Bind(listenerEndPoint);
            // and start listening for incoming connections
            listenerSocket.Listen(10);


            Microsoft.SPOT.Net.NetworkInformation.NetworkInterface
                networkInterface =
                    Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.
                        GetAllNetworkInterfaces()[0];

            Debug.Print("my ip address: " + networkInterface.IPAddress.ToString());
            Debug.Print("listening and getting inside the Loop.. $$$$");

            // listen for and process incoming requests
            while (true)
            {
                Debug.Print(".");

                // wait for a client to connect
                Socket clientSocket = listenerSocket.Accept();
                // wait for data to arrive
                bool dataReady = clientSocket.Poll(5000000, SelectMode.SelectRead);


                // if dataReady is true and there are bytes available to read,
                // then you have a good connection.
                if (dataReady && clientSocket.Available > 0)
                {
                    byte[] buffer = new byte[clientSocket.Available];
                    int bytesRead = clientSocket.Receive(buffer);
                    string request =
                        new string(System.Text.Encoding.UTF8.GetChars(buffer));

                    Debug.Print(request);

                    if (request.IndexOf("ON") >= 0)
                    {
                        led.Write(true);
                    }
                    else if (request.IndexOf("OFF") >= 0)
                    {
                        led.Write(false);
                    }

                    string statusText = "LED is " + (led.Read() ? "ON" : "OFF") + ".";
                    // return a message to the client letting it
                    // know if the LED is now on or off.
                    string response =
                        "HTTP/1.1 200 OK\r\n" +
                        "Content-Type: text/html; charset=utf-8\r\n\r\n" +
                        "<html><head><title>Netduino Plus LED Sample</title></head>" +
                        "<body>" + statusText + "</body></html>";
                    clientSocket.Send(System.Text.Encoding.UTF8.GetBytes(response));

                }
                // important: close the client socket
                clientSocket.Close();

            }

        }

    }
}
